// api由这个页面控制
// https://wx62f925564f6d32a7.bank-account.hndyjr.com/lianyuan/#/ 正式项目地址
// const baseUrl = 'wxc1d8a420c4462b33.bank-account.hndyjr.com/xjxqApi' //测试
const baseUrl = 'https://coupon.hndyjr.com/couponMsApi/app' //测试
const request = (url = '', date = {}, type = 'GET', header = {}, ) => {
	// let token = uni.getStorageSync('token')
	let token = sessionStorage.getItem('token')
	uni.showLoading({
		title: '数据加载中...',
		mask: true
	});
	const headerData = {
		'content-type': 'application/json;charset:utf-8',
		'token': token
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: type,
			url: baseUrl + url,
			data: date,
			header: headerData,
			dataType: 'json',
		}).then((response) => {
			setTimeout(function() {
				uni.hideLoading();
			}, 200);
			let [error, res] = response;
			console.log(response)
			if (response[1].data.code == 401) {
				//#ifdef H5
				let url = window.location.href
				uni.setStorageSync('localUrl', url);
				checkWeChatCode()
				//#endif
			}
			resolve(res.data);
		}).catch(error => {
			console.log(error)
			let [err, res] = error;
			reject(err)
		})
	});
}

function checkWeChatCode() {
	let code = getUrlCode('code')
	if (code) {
		// getOpenidAndUserinfo(code)
	} else {
		getWeChatCode()
	}
}

function getOpenidAndUserinfo(code) {
	uni.request({
		method: 'POST',
		url: baseUrl + '/auth/loginByMp',
		data: {
			'code': code,
			'projectId':'zjjjhyl',
			'scope':1 // 静默登录才传scope，授权不需要scope
		},
		header: {
			'content-type': 'application/json'
		},
		success: res => {
			console.log(res)
			// uni.setStorageSync('token', res.data.token);
			sessionStorage.setItem('token',res.data.token)
			uni.setStorageSync('user', res.data.user);
			uni.setStorageSync('openId', res.data.openId);
		}
	})
}

function getWeChatCode() {
	let url = window.location.href.split('#')[0] + '#/pages/weixin/switch'
	uni.setStorageSync('url', url);
	let local = encodeURIComponent(url); // 获取当前页面地址作为回调地址 
	uni.setStorageSync('local', local);
	// 测试环境用的也是正式appid
	let appid = 'wxc8a6de38f8b6b12d' //测试appid
	// 通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	window.location.href =
		"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
		appid +
		"&redirect_uri=" +
		local +
		"&response_type=code&scope=snsapi_base&state=STATE&component_appid=wx5004da269c72ac92#wechat_redirect";
		// scope=snsapi_userinfo 授权登录  scope=snsapi_base 静默登录
}

function getUrlCode(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
			''
		])[1]
		.replace(/\+/g, '%20')) || null
}
export default request
